package com.elock.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.elock.base.core.Pageable;
import com.elock.base.core.dao.impl.DaoCenter;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.WebUtils;
import com.elock.entity.SaleOrg;
import com.elock.service.MemberService;

/**
 * Dao - 组织
 * 
 * @author 仁德
 */
@Repository("saleOrgBaseDao")
public class SaleOrgBaseDao extends DaoCenter {

	@Resource(name = "memberServiceImpl")
	private MemberService memberService;

	/**
	 * 查找下级组织
	 * 
	 * @param name
	 * @param isEnabled
	 * @param saleOrg
	 * @param count
	 * @return
	 */
	public List<SaleOrg> findChildren(String name, Boolean isEnabled, SaleOrg saleOrg, int count) {

		List<Object> list = new ArrayList<Object>();
		String sql = "select * from sale_org where 1=1";
		if (saleOrg != null) {
			sql += " and tree_path like ?";
			list.add("%" + SaleOrg.ID_PATH_SEPARATOR + saleOrg.getId() + SaleOrg.ID_PATH_SEPARATOR + "%");
		}
		if (name != null) {
			sql += " and name like ?";
			list.add("%" + name + "%");
		}
		if (isEnabled != null) {
			if (isEnabled)
				sql += " and is_enabled = 1";
			else
				sql += " and is_enabled = 0";
		}

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}

		List<SaleOrg> saleOrgs = getNativeDao().findListManaged(sql, objs, count, SaleOrg.class);
		return sort(saleOrgs, saleOrg);
	}

	/**
	 * 排序组织
	 */
	private List<SaleOrg> sort(List<SaleOrg> saleOrgs, SaleOrg parent) {
		List<SaleOrg> result = new ArrayList<SaleOrg>();
		if (saleOrgs != null) {
			for (SaleOrg saleOrg : saleOrgs) {
				if ((saleOrg.getParent() != null && saleOrg.getParent().equals(parent))
						|| (saleOrg.getParent() == null && parent == null)) {
					result.add(saleOrg);
					result.addAll(sort(saleOrgs, saleOrg));
				}
			}
		}
		return result;
	}

	public List<Map<String, Object>> findList(String saleOrgName, String sn, Boolean isEnabled, Pageable pageable) {
		List<Object> list = new ArrayList<Object>();
		Long companyInfoId = WebUtils.getCurrentCompanyInfoId();
		StringBuilder sql = new StringBuilder();
		// if (ConvertUtil.isEmpty(saleOrgName)) {
		// sql.append(
		// "select s.*,sd.value, 0 as is_search from sale_org s left join
		// system_dict sd on s.type = sd.id and sd.parent is not null");
		// sql.append(
		// " where s.id = (select sale_org from member_sale_org t where t.member
		// = ?)");
		// list.add(memberService.getCurrent().getId());
		// }
		// else {
		// sql.append(
		// "select s.*,sd.value,1 as is_search from sale_org s left join
		// system_dict sd on s.type = sd.id and sd.parent is not null");
		// sql.append(" where s.id in (" + saleOrgAuth() + ")");
		// }
		if (ConvertUtil.isEmpty(saleOrgName)) {
			sql.append(
					"select s.*,sd.value, 0 as is_search from sale_org s left join system_dict sd on s.type = sd.id and sd.parent is not null where s.parent is null");
		} else {
			sql.append(
					"SELECT s.*,sd.value,1 as is_search from sale_org s left join system_dict sd on s.type = sd.id and sd.parent is not null WHERE 1=1");
		}

		if (companyInfoId != null) {
			sql.append(" and s.company_info_id=?");
			list.add(companyInfoId);
		}
		if (!ConvertUtil.isEmpty(saleOrgName)) {
			sql.append(" and s.name like ?");
			list.add("%" + saleOrgName + "%");
		}
		if (!ConvertUtil.isEmpty(sn)) {
			sql.append(" and s.sn like ?");
			list.add("%" + sn + "%");
		}
		if (isEnabled != null) {
			if (isEnabled)
				sql.append(" and s.is_enabled = 1");
			else
				sql.append(" and s.is_enabled = 0");
		}

		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}
		List<Map<String, Object>> saleOrgs = getNativeDao().findListMap(sql.toString(), objs, 0);
		String cSql = "";
		for (Map<String, Object> saleOrg : saleOrgs) {
			String tree_path_name = "";
			String tree_path = saleOrg.get("tree_path").toString();
			if (tree_path.length() > 1) {
				tree_path = tree_path.substring(1);
				tree_path = tree_path.substring(0, tree_path.length() - 1);
				cSql = "select group_concat(name separator ' / ') tree_path_name from sale_org where id in ("
						+ "SELECT id from sale_org so WHERE so.id in(" + tree_path + ") ORDER BY so.grade asc" + ")";
				tree_path_name = getNativeDao().findString(cSql, null);
			}
			saleOrg.put("tree_path_name", tree_path_name);
		}

		return saleOrgs;

	}

	public List<Map<String, Object>> findChildren(Long parentId) {

		String sql = "select p.*,sd.value, 0 as is_search from sale_org p left join system_dict sd on p.type = sd.id and sd.parent is not null where p.parent = ?";
		List<Map<String, Object>> productCategories = getNativeDao().findListMap(sql, new Object[] { parentId }, 0);

		return productCategories;
	}

	public SaleOrg findByStoreMember(Long storeMemberId) {
		List<Object> list = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder();
		sql.append(
				"select so.* from store_member_sale_org smso left join sale_org so on so.id=smso.sale_org where 1=1");
		if (storeMemberId != null) {
			sql.append(" and smso.store_member = ?");
			list.add(storeMemberId);
		}
		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}
		SaleOrg saleOrg = getNativeDao().findSingleManaged(sql.toString(), objs, SaleOrg.class);
		return saleOrg;
	}

	public String saleOrgAuth() {

		String sql = "select sale_org from member_sale_org t where t.member = ?";
		Long saleOrgId = getNativeDao().findLong(sql, new Object[] { memberService.getCurrent().getId() });
		sql = "select id from sale_org where id = " + saleOrgId + " or tree_path like '%," + saleOrgId + ",%'";
		return sql;
	}

	public int sameSaleOrgSn(String sn, Long id) {
		List<Object> list = new ArrayList<Object>();
		StringBuilder sql = new StringBuilder();
		sql.append("select count(id) from sale_org where sn=?");
		list.add(sn);
		if (id != null) {
			sql.append(" and id<>?");
			list.add(id);
		}
		Object[] objs = new Object[list.size()];
		for (int i = 0; i < list.size(); i++) {
			objs[i] = list.get(i);
		}
		int count = getNativeDao().findInt(sql.toString(), objs);
		return count;
	}
}